#include <stdio.h>
#include <string.h>
#include "typedef.h"
#include "common.h"
#include "env.h"
#include "log.h"

#define LOG_MSG_MAX_LEN (1024)

static const char* LOG_ALERT_FILENAME = "tmc_error.log";
static const char* LOG_INFOR_FILENAME = "tmc_jobs.log";

static const char* FM_FILEPATH  = "%s\\%s\0";
static const char* FM_ALERT_MSG = "[%s] [%s] %s\n\0";
static const char* FM_INFOR_MSG = "";
static const char* FM_TIMES_MSG = "%a %b %d %H:%M:%S %Y";

static const char* msg_type_table[] = {"NONE", "ERROR", "WARNING", "NOTICE"};

static FILE *fp_alert = NULL;
static FILE *fp_infor = NULL;

/*
 * Initialize the log file system.
 */
int log_init()
{
#ifdef LOGON
	char* filepath1 = {"/var/log/tmc_error.log"};
#if 0
	sprintf( filepath,
			 FM_FILEPATH,
			 g_log_folder_path,
			 LOG_ALERT_FILENAME
			 );
#endif
	if ( (fp_alert = fopen( filepath1, "a" )) == NULL )
	{
		return ERROR;
	}

	char* filepath2 = {"/var/log/tmc_jobs.log"};
#if 0
	sprintf( filepath,
			 FM_FILEPATH,
			 g_log_folder_path,
			 LOG_INFOR_FILENAME);
#endif
	if ( (fp_infor = fopen( filepath2, "a" )) == NULL )
	{
		return ERROR;
	}
#endif
	return SUCCESS;
}

/*
 * Alert  interface.
 */
void log_alert(int type, const char* message)
{
	//
	// 1. get the local time.
	char tm[MAX_PATH] = {0};
	getlocaltime( tm, MAX_PATH, FM_TIMES_MSG);

	//
	// 2. get the type message.
	char* typestr = (char*)msg_type_table[0];
	if ( type > 0
		 && type < ( sizeof(msg_type_table) / sizeof (msg_type_table[0])) ){
		typestr = (char*)msg_type_table[type];
	}

	//
	// 3. format the message.
	char buffer[LOG_MSG_MAX_LEN] = {0};
	sprintf ( buffer,
			  FM_ALERT_MSG,
			  tm,
			  typestr,
			  message
			  );

#ifdef LOGON
    //
	// 4. write to file.
	fputs( buffer , fp_alert );

    // 5. flsuh to file.
    fflush( fp_alert );
#else
	printf(buffer);
#endif
}

/*
 * Release the file
 */
void log_release()
{
#ifdef LOGON
	if ( fp_alert != NULL )
	{
		fclose(fp_alert);
	}

	if ( fp_infor != NULL )
	{
		fclose(fp_infor);
	}
#endif
}
